package com.example.keli.ui.home.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.keli.MainActivity;
import com.example.keli.R;
import com.example.keli.api.HttpUtils;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.utils.CopyUtil;
import com.example.keli.base.utils.DataUtil;
import com.example.keli.base.utils.DensityUtil;
import com.example.keli.base.utils.DialogUtil;
import com.example.keli.base.utils.GlideUtil;
import com.example.keli.base.utils.PayUtil;
import com.example.keli.base.utils.Spanny;
import com.example.keli.base.utils.ViewPagerHelper;
import com.example.keli.base.widget.CircleNavigator;
import com.example.keli.base.widget.GiftPopWindow;
import com.example.keli.base.widget.MagicIndicator;
import com.example.keli.ui.common.ShareActivity;
import com.example.keli.ui.home.adapter.GoodActorAdapter;
import com.example.keli.ui.home.adapter.UserListAdapter;
import com.example.keli.ui.home.model.DetailUserData;
import com.example.keli.ui.home.model.GoodActorData;
import com.example.keli.ui.home.model.ObjectVo;
import com.example.keli.ui.home.model.PaySucData;
import com.example.keli.ui.my.model.OrderVO;
import com.flyco.roundview.RoundRelativeLayout;
import com.flyco.roundview.RoundTextView;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;

/**
 * description: 对象详情页
 * author: Allen
 * date: 2019/3/22 14:47
 */
public class ObjectDetailActivity extends BaseActivity {

    @BindView(R.id.rootView)
    RelativeLayout rootView;
    @BindView(R.id.toolbar_subtitle)
    TextView mToolbarSubtitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.appbar)
    LinearLayout mAppbar;
    @BindView(R.id.viewpager)
    ViewPager mViewpager;
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.praise)
    ImageView mPraise;
    @BindView(R.id.iv_portrait)
    ImageView mIvPortrait;
    @BindView(R.id.tablayout)
    SegmentTabLayout mTablayout;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerview;

    String uid = "";
    String aaid = "";
    @BindView(R.id.nickname)
    TextView mNickname;
    @BindView(R.id.userinfo)
    TextView mUserinfo;
    @BindView(R.id.gender)
    ImageView mGender;
    @BindView(R.id.age)
    RoundTextView mAge;
    @BindView(R.id.add_weixin)
    RoundRelativeLayout mAddWeixin;
    @BindView(R.id.good_recyclerview)
    RecyclerView goodRecyclerview;
    @BindView(R.id.indicator)
    MagicIndicator indicator;
    @BindView(R.id.gift_num)
    TextView giftNum;
    @BindView(R.id.vote)
    LinearLayout vote;
    @BindView(R.id.jump_home)
    ImageView jumpHome;
    @BindView(R.id.add_weixin_layout)
    LinearLayout addWeixinLayout;
    @BindView(R.id.wechat_code)
    TextView wechatCode;
    @BindView(R.id.copy_wechat)
    RoundTextView copyWechat;
    @BindView(R.id.time_out)
    TextView timeOut;
    @BindView(R.id.wechat_layout)
    LinearLayout wechatLayout;
    @BindView(R.id.mark_code)
    TextView markCode;
    @BindView(R.id.copy_mark)
    RoundTextView copyMark;
    @BindView(R.id.mark_layout)
    LinearLayout markLayout;

    private String[] mTitles = {"优秀作品", "贡献排行"};
    UserListAdapter userAdapter;
    GoodActorAdapter goodAdapter;
    String is_like = "false";
    String by_uid = "";
    String nick_name = "";
    String imgUrl = "";

    private GiftPopWindow popWindow;
    private String order_sn = "";//订单号
    private ObjectVo mObjectVo;
    private String flag = "gift";//区分是微信号，还是礼物支付。礼物是gift，微信是wechat

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReadyPay(OrderVO event) {
        order_sn = event.getOrder_sn();
    }

    public static void start(Context context, String uid, String aaid) {
        Intent intent = new Intent(context, ObjectDetailActivity.class);
        intent.putExtra("uid", uid);
        intent.putExtra("aaid", aaid);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_object_detail;
    }

    @Override
    protected void bindData() {
        EventBus.getDefault().register(this);
        uid = getIntent().getStringExtra("uid");
        aaid = getIntent().getStringExtra("aaid");
        getActivityUserInfo();

        mTablayout.setTabData(mTitles);
        mRecyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        goodRecyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        userAdapter = new UserListAdapter(mUserList);
        goodAdapter = new GoodActorAdapter(mGoodList, ObjectDetailActivity.this);
        mRecyclerview.setAdapter(userAdapter);
        goodRecyclerview.setAdapter(goodAdapter);
        getGoodActor();

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void bindListener() {
        mTablayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                switch (position) {
                    case 0:
                        goodRecyclerview.setVisibility(View.VISIBLE);
                        mRecyclerview.setVisibility(View.GONE);
                        getGoodActor();
                        break;
                    case 1:
                        goodRecyclerview.setVisibility(View.GONE);
                        mRecyclerview.setVisibility(View.VISIBLE);
                        getActorLikeList();
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        goodAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ObjectDetailActivity.start(ObjectDetailActivity.this, String.valueOf(mGoodList.get(position).getUid()), String.valueOf(mGoodList.get(position).getAaid()));
            }
        });
    }

    @OnClick({R.id.praise, R.id.add_weixin, R.id.vote, R.id.jump_home, R.id.toolbar_subtitle})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.praise:
                setLike();
                break;
            case R.id.add_weixin:
                //添加微信
                flag = "wechat";
                PayUtil.wechatPayOnlyGift(this, by_uid, aaid, "h5");
                break;
            case R.id.vote:
                //投票
                flag = "gift";
                if (popWindow == null) {
                    popWindow = new GiftPopWindow(this);
                }
                popWindow.showPopupWindow(rootView, by_uid, aaid);
                break;
            case R.id.jump_home:
                //主页
                MainActivity.start(ObjectDetailActivity.this);
                break;
            case R.id.toolbar_subtitle:
                if (mImageUrl.size() > 0) {
                    imgUrl = mImageUrl.get(0);
                }
                ShareActivity.start(ObjectDetailActivity.this, uid, aaid, nick_name, imgUrl);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(order_sn)) {
            getGiftOrder(order_sn);
            order_sn = "";
        }
    }

    private void getGiftOrder(String order_sn) {
        Map<String, String> map = new HashMap<>();
        map.put("order_sn", order_sn);
        HttpUtils.ApiFunc(RetrofitManager.mApiService.getGiftOrder(map), new SubscriberListener<BaseResponse<PaySucData>>() {
            @Override
            public void onSuccess(BaseResponse<PaySucData> objectBaseResponse) {
                showPayResultDailog(true);
                getWeChat();
                getActorLikeList();
            }

            @Override
            public void onFailer(String msg) {
                showPayResultDailog(false);
            }

            @Override
            public void onTokenError() {
                showPayResultDailog(false);
            }
        });
    }

    private void getWeChat() {
        Map<String, String> map = new HashMap<>();
        map.put("by_uid", by_uid);
        map.put("order_type", "gift");
        HttpUtils.ApiFunc(RetrofitManager.mApiService.getGiftOrder(map), new SubscriberListener<BaseResponse<PaySucData>>() {
            @Override
            public void onSuccess(BaseResponse<PaySucData> response) {
                if(response.getData()!=null){
                    if(!TextUtils.isEmpty(response.getData().getWechat())){
                        int lastDays = DataUtil.getLastDay(Integer.parseInt(response.getData().getGet_wechat_day()), response.getData().getGet_wechat_time());
                        if (lastDays > 0){
                            //剩余lastDays天
                            addWeixinLayout.setVisibility(View.GONE);
                            wechatLayout.setVisibility(View.VISIBLE);
                            markLayout.setVisibility(View.VISIBLE);
                            wechatCode.setText(response.getData().getWechat());
                            markCode.setText("备注码："+response.getData().getLove_code());
                            timeOut.setText("有效时间剩余"+response.getData().getGet_wechat_day()+"天");
                        }
                    }
                }
            }

            @Override
            public void onFailer(String msg) {
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    private void showPayResultDailog(final boolean success) {
        View view = getLayoutInflater().inflate(R.layout.pay_result_dialog, null);
        ImageView iv_result = view.findViewById(R.id.iv_result);
        TextView tv_result = view.findViewById(R.id.tv_result);
        ImageView iv_close = view.findViewById(R.id.iv_close);
        final Dialog dialog = DialogUtil.whiteCenterDialog(getActivity(), view);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog != null) {
                    dialog.dismiss();
                    if (success) {
                        switch (flag) {
                            case "wechat":
                                showBottomDialog(false);
                                break;
                            case "gift":
                                showBottomDialog(true);
                                break;
                        }
                    }
                }
            }
        });

        tv_result.setText(success ? "支付成功" : "支付失败");
        iv_result.setImageResource(success ? R.mipmap.pay_success : R.mipmap.pay_failer);
        dialog.show();
    }

    private void getActivityUserInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("aaid", aaid);
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.getActivityUserInfo(map), new SubscriberListener<BaseResponse<ObjectVo>>() {
            @Override
            public void onSuccess(BaseResponse<ObjectVo> response) {
                mToolbarSubtitle.setText("邀请朋友");
                setHeaderView(response.getData());
                nick_name = response.getData().getNickname();
                mNickname.setText(getSpanny(nick_name, "(ID：" + response.getData().getCode() + ")"));
                mUserinfo.setText(response.getData().getRegion_name() + " /" + response.getData().getHeight() + " /" + response.getData().getPosition());

                if (TextUtils.equals(response.getData().getSex(), "2")) {
                    mGender.setImageResource(R.mipmap.female_icon);
                }else if(TextUtils.equals(response.getData().getSex(), "1")){
                    mGender.setImageResource(R.mipmap.male_icon);
                }
                is_like = response.getData().getIs_like();
                if (TextUtils.equals(is_like, "false")) {
                    mPraise.setSelected(false);
                } else {
                    mPraise.setSelected(true);
                }
                giftNum.setText(String.valueOf(response.getData().getGift_num()));
                mAge.setText(String.valueOf(response.getData().getAge()));
                mTitle.setText(response.getData().getContent());

                by_uid = String.valueOf(response.getData().getUid());
                abTitle.setText(response.getData().getNickname() + "的参赛信息");
                getWeChat();
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }


    List<DetailUserData.UserInfoBean> mUserList = new ArrayList<>();
    List<GoodActorData.DataBean> mGoodList = new ArrayList<>();

    //参赛者投票榜单
    private void getActorLikeList() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", uid);
        map.put("aaid", aaid);
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.getActorLikeList(map), new SubscriberListener<BaseResponse<DetailUserData>>() {
            @Override
            public void onSuccess(BaseResponse<DetailUserData> response) {
                mUserList.clear();
                mUserList.addAll(response.getData().getUserInfo());
                userAdapter.notifyDataSetChanged();
                userAdapter.removeAllFooterView();
                if (response.getData().getUserInfo().size() > 0) {
                    setFootView();
                }
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }

    private void getGoodActor() {
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.getGoodActor(), new SubscriberListener<BaseResponse<GoodActorData>>() {
            @Override
            public void onSuccess(BaseResponse<GoodActorData> response) {
                mGoodList.clear();
                mGoodList.addAll(response.getData().getData());
                goodAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }

    private void setLike() {
        startProgressDialog();
        Map<String, String> map = new HashMap<>();
        map.put("by_uid", by_uid);
        HttpUtils.ApiFunc(RetrofitManager.mApiFunc.setLike(map), new SubscriberListener<BaseResponse<Object>>() {
            @Override
            public void onSuccess(BaseResponse<Object> response) {
                stopProgressDialog();
                if (TextUtils.equals(is_like, "false")) {
                    is_like = "true";
                    mPraise.setSelected(true);
                } else {
                    is_like = "false";
                    mPraise.setSelected(false);
                }
            }

            @Override
            public void onFailer(String msg) {
                stopProgressDialog();
                toast(msg);
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    View mCoverView;
    ImageView mCoverImage;
    ImageView mVideoIcon;
    List<String> mImageUrl = new ArrayList<>();
    List<View> mViewList = new ArrayList<>();

    private void setHeaderView(final ObjectVo objectVo) {
//        mImageUrl.add(objectVo.getCover_picture());
        mImageUrl.addAll(Arrays.asList(objectVo.getImg().split(",")));
        if (mImageUrl.size() > 0) {
            mImageUrl.add(0, mImageUrl.get(0));
        }
        for (int i = 0; i < mImageUrl.size(); i++) {

            if (i == 0) {
                mCoverView = LayoutInflater.from(this).inflate(R.layout.diy_object_detail_video_layout, null);
                JCVideoPlayerStandard video_player = mCoverView.findViewById(R.id.video_player);
                mCoverImage = video_player.thumbImageView;
                mCoverImage.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                mCoverImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
                video_player.backButton.setVisibility(View.GONE);
                video_player.setUp(objectVo.getVideo(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
            } else {
                mCoverView = LayoutInflater.from(this).inflate(R.layout.diy_object_detail_image_layout, null);
                mCoverImage = mCoverView.findViewById(R.id.cover);
                mVideoIcon = mCoverView.findViewById(R.id.video_icon);
                mVideoIcon.setVisibility(View.GONE);
            }
            GlideUtil.displayRound(ObjectDetailActivity.this, mCoverImage, mImageUrl.get(i), 10);
            mViewList.add(mCoverView);
        }
        mViewpager.setAdapter(pagerAdapter);
        initIndicator();
    }

    private void initIndicator() {
        CircleNavigator circleNavigator = new CircleNavigator(this);
        circleNavigator.setCircleCount(pagerAdapter.getCount());
        circleNavigator.setCircleColor(ContextCompat.getColor(ObjectDetailActivity.this, R.color.cicle_bg));
        circleNavigator.setCircleSelectColor(ContextCompat.getColor(ObjectDetailActivity.this, R.color.yellow_text));
        circleNavigator.setCircleClickListener(new CircleNavigator.OnCircleClickListener() {
            @Override
            public void onClick(int index) {
                mViewpager.setCurrentItem(index);
            }
        });
        indicator.setNavigator(circleNavigator);
        ViewPagerHelper.bind(indicator, mViewpager);
    }

    PagerAdapter pagerAdapter = new PagerAdapter() {
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position));
            return mViewList.get(position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return mViewList.size();
        }
    };


    private Spanny getSpanny(String front, String back) {
        Spanny spanny = new Spanny(front, new ForegroundColorSpan(ContextCompat.getColor(this, R.color.white)), new AbsoluteSizeSpan(16, true))
                .append(back, new ForegroundColorSpan(ContextCompat.getColor(this, R.color.white)), new AbsoluteSizeSpan(11, true));
        return spanny;
    }

    private void setFootView() {
        TextView mFootView = new TextView(this);
        mFootView.setText("查看更多排名 >");
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(40));
        mFootView.setLayoutParams(layoutParams);
        mFootView.setGravity(Gravity.CENTER);
        userAdapter.addFooterView(mFootView);
        mFootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContributeActivity.start(ObjectDetailActivity.this, uid, aaid, nick_name);
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void onBackPressed() {
        if (JCVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        JCVideoPlayer.releaseAllVideos();
    }

    @OnClick({R.id.copy_wechat, R.id.copy_mark})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.copy_wechat:
                CopyUtil.copy(ObjectDetailActivity.this,wechatCode.getText().toString());
                toast("复制成功");
                break;
            case R.id.copy_mark:
                CopyUtil.copy(ObjectDetailActivity.this,markCode.getText().toString());
                toast("复制成功");
                break;
        }
    }

    private void showBottomDialog(final boolean isGift) {
        View view = getLayoutInflater().inflate(R.layout.pay_succ_tip_dialog, null);
        ImageView icon = view.findViewById(R.id.icon);
        final TextView time = view.findViewById(R.id.count_down);
        TextView text = view.findViewById(R.id.text_des);
        final Dialog dialog = DialogUtil.getMenuDialog(getActivity(), view);
        new CountDownTimer(4*1000,1000){

            @Override
            public void onTick(long millisUntilFinished) {
                time.setText((millisUntilFinished/1000)+"s");
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        }.start();
        text.setText(isGift ? "已为您喜爱的ta投票助力成功" : "专属礼物送出成功，已获得微信号");
        icon.setImageResource(isGift ? R.mipmap.liwu : R.mipmap.zuanshi);
        dialog.show();
    }
}
